package com.qfedu.sca.controller;

import cn.hutool.core.io.IoUtil;
import com.qfedu.sca.common.vo.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/7 14:30
 * @Modified:
 */
@RestController
@RequestMapping("server/hello")
@RefreshScope //监听 自动获取配置中心
public class HelloController {
    @Value("${newnum}") //属性注入 获取对应配置文件的内容
    private Integer num;
    @GetMapping("hi")
    public String hi(){
        return num+"幸运数字："+new Random().nextInt(10);
    }

    @PostMapping("upload")
    public R upload(@RequestPart MultipartFile file, HttpServletRequest request) throws IOException {
        if(!file.isEmpty()){
            String path=request.getServletContext().getRealPath("imgs");
            File file1=new File(path);
            if(!file1.exists()){
                file1.mkdirs();
            }

            String fname= System.currentTimeMillis()+"_"+file.getOriginalFilename();
            FileOutputStream fos=new FileOutputStream(new File(file1,fname));
            fos.write(file.getBytes());

            return R.ok(path+"/"+fname);
        }
        return R.fail("亲，文件上失败！");

    }
}
